package com.crm.system.service.impl.user;

import com.alibaba.fastjson.JSONObject;
import com.crm.common.constant.ProjectBusinessConstant;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.util.CheckPasswordUtils;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.common.util.SendEamil;
import com.crm.model.entity.sys.ImportFailureLog;
import com.crm.model.entity.sys.UpdatePsw;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.entity.sys.UserInfo;
import com.crm.model.entity.sys.permissionManagement.SysAccountPermission;
import com.crm.model.entity.sys.permissionManagement.SysCompany;
import com.crm.model.qo.sys.UserAccountQO;
import com.crm.model.vo.sys.ImportFailureLogVO;
import com.crm.model.vo.systemManager.UserAccountImportVO;
import com.crm.model.vo.user.UserAccountAddQO;
import com.crm.model.vo.user.UserAccountManagerVO;
import com.crm.model.vo.user.UserAccountVO;
import com.crm.redis.service.user.UserAccountRedisService;
import com.crm.service.sys.ImportFailureLogDbService;
import com.crm.service.sys.UpdatePswDbService;
import com.crm.service.sys.UserAccountDbService;
import com.crm.service.sys.UserInfoDbService;
import com.crm.service.sys.permissionManagement.SysAccountPermissionDbService;
import com.crm.service.sys.permissionManagement.SysCompanyDbService;
import com.crm.system.service.permissionManagement.SysAccountPermissionService;
import com.crm.system.service.user.UserAccountService;
import com.crm.system.service.user.UserInfoService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @author luojie
 * @date 2020/11/13 9:33
 */
@Service
public class UserAccountServiceImpl implements UserAccountService {

    @Autowired
    UserAccountDbService userAccountDbService;
    @Autowired
    private UserInfoService userInfoService;
    @Autowired
    SysCompanyDbService sysCompanyDbService;
    @Autowired
    SysAccountPermissionService sysAccountPermissionService;
    @Autowired
    SysAccountPermissionDbService sysAccountPermissionDbService;
    @Autowired
    ImportFailureLogDbService importFailureLogDbService;

    @Autowired
    UserAccountRedisService userAccountRedisService;
    @Autowired
    UserInfoDbService userInfoDbService;

    @Autowired
    UpdatePswDbService updatePswDbService;

    @Override
    public UserAccount selectUserAccountByUserName(String userName) {
        UserAccount userAccount = userAccountDbService.selectUserAccountByUserAccount(userName);
        return userAccount;
    }

    /**
     * 修改：accountId为空时获取当前登陆用户
     *
     * @param accountId
     * @return
     * @Author renshaorong
     * @Date 2021/4/21
     */
    @Override
    public UserAccount selectUserAccountByAccountId(String accountId) {
        UserAccount userAccount;
        if (StringUtils.isEmpty(accountId)) {
            userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        } else {
            userAccount = userAccountDbService.selectUserAccountByAccountId(accountId);
        }
        return userAccount;
    }

    @Override
    public List<HashMap> selectUserAccountByDeptId(String deptId) {
        List<HashMap> hashMaps = new ArrayList<HashMap>();
        List<UserAccount> accounts = userAccountDbService.selectUserAccountListByDeptId(deptId);
        accounts.stream().forEach(account -> {
            HashMap hashMap = new HashMap();
            hashMap.put("userId", account.getAccountId());
            hashMap.put("userName", account.getUserName());
            hashMaps.add(hashMap);
        });
        return hashMaps;
    }

    @Override
    public List<UserAccount> selectUserAccountByCompanyId(String companyId) {
            List<UserAccount> userAccounts = userAccountDbService.selectUserAccountByCompanyId(companyId);
            return userAccounts;

    }

    @Override
    public List<UserAccount> getAccountByCompanyIdExcludeLoginPerson(String companyId) {
        List<UserAccount> userAccounts = userAccountDbService.selectUserAccountByCompanyIdExcludeLoginPerson(companyId);
        return userAccounts;
    }

    /***
     * @Description:按照公司id获取分页的账号列表
     * @Param: 公司id
     * @Author: luojie
     * @Date: 2021/8/18 14:23
     */
    @Override
    public List<UserAccount> getAccountListPageByCompanyId(Integer pageIndex,Integer pageSize,String companyId,String userName) {
        List<UserAccount> userAccounts = userAccountDbService.getAccountListPageByCompanyId(companyId,userName);
        return userAccounts;
    }

    /**
     * 根据公司id获取在职且未禁用账号列表
     * @Author renshaorong
     * @Date 2021/7/13
     */
    @Override
    public List<UserAccountManagerVO> getAbleAccountListByCompanyId(String companyId) {
        List<UserAccountManagerVO> userAccounts = userAccountDbService.getAbleAccountListByCompanyId(companyId);
        return userAccounts;
    }

    @Override
    public List<UserAccountVO> getAllCoDeveloper() {
        List<UserAccountVO> userAccountVOList = new ArrayList<>();
        List<UserAccount> userAccounts = userAccountDbService.getAllCoDeveloper();
        userAccounts.stream().forEach(userAccount -> {
            UserAccountVO userAccountVO = new UserAccountVO();
            userAccountVO.setUserId(userAccount.getAccountId());
            userAccountVO.setUserName(userAccount.getUserName());
            //查询用户电话号
            UserInfo userInfo = userInfoService.selectUserInfoByPrivateKey(userAccount.getUserId());
            if (userInfo != null) {
                userAccountVO.setUserContact(userInfo.getUserContact());
            }
            userAccountVOList.add(userAccountVO);
        });
        return userAccountVOList;
    }


    @Override
    public List<Map<String, Object>> selectUserAccountList(String permissionGroupId) {
        UserAccount account = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        //包装zTree
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map = null;
        if (account != null) {
            boolean isAdmin = CommonUtils.isAdmin(account.getUserId());
            //获取所有账号
            List<UserAccount> userAccountList = userAccountDbService.selectUserAccountList();
            //根据公司ID进行分组
            Map<String, List<UserAccount>> userAccountMap = userAccountList.stream().collect(Collectors.groupingBy(userAccount -> userAccount.getCompanyId()));
            //获取所有公司
            List<SysCompany> sysCompanyList = sysCompanyDbService.selectSysCompanyList();
            //根据权限组ID获取对应账号
            List<SysAccountPermission> sysAccountPermissionList = sysAccountPermissionService.selectSysAccountPermissionList(permissionGroupId, null);
            //根据账号ID进行分组
            Map<String, List<SysAccountPermission>> sysAccountPermissionMap = sysAccountPermissionList.stream().collect(Collectors.groupingBy(sysAccountPermission -> sysAccountPermission.getAccountId()));

            if (isAdmin) {
                //超级管理员
                for (SysCompany sysCompany : sysCompanyList) {
                    list = generateZTree(permissionGroupId, list, userAccountMap, sysAccountPermissionMap, sysCompany, account);
                }
                //账号没有对应的公司
                for (String companyId : userAccountMap.keySet()) {
                    boolean isHaveCompany = isHaveCompany(sysCompanyList, companyId);
                    if (!isHaveCompany) {
                        List<UserAccount> userAccounts = userAccountMap.get(companyId);
                        if (userAccounts != null && !userAccounts.isEmpty()) {
                            for (UserAccount userAccount : userAccounts) {
                                map = new HashMap<>();
                                map.put("id", userAccount.getAccountId());
                                map.put("pId", "b98922598ba811eb9e0a00163e08893dads");
                                map.put("name", userAccount.getUserName());
                                map.put("accountIdentification", "1");
                                List<SysAccountPermission> sysAccountPermissions = sysAccountPermissionMap.get(userAccount.getAccountId());
                                boolean isHavePermissions = isHavePermissions(permissionGroupId, sysAccountPermissions);
                                if (isHavePermissions) {
                                    map.put("checked", true);
                                }
                                list.add(map);
                            }
                        }
                    }
                }
            } else {
                //非超级管理员
                for (SysCompany sysCompany : sysCompanyList) {
                    if (account.getCompanyId() != null && account.getCompanyId().equals(sysCompany.getCompanyId())) {
                        list = generateZTree(permissionGroupId, list, userAccountMap, sysAccountPermissionMap, sysCompany, account);
                    }
                }

            }
        }
        return list;
    }

    /**
     * 账号是否有对应的公司
     *
     * @param sysCompanyList
     * @param companyId
     * @return
     */
    private boolean isHaveCompany(List<SysCompany> sysCompanyList, String companyId) {
        boolean flag = false;
        for (SysCompany sysCompany : sysCompanyList) {
            if (companyId.equals(sysCompany.getCompanyId())) {
                flag = true;
                break;
            }
        }
        return flag;
    }

    /**
     * 生成zTree
     *
     * @param permissionGroupId
     * @param list
     * @param userAccountMap
     * @param sysAccountPermissionMap
     * @param sysCompany
     * @return
     */
    private List<Map<String, Object>> generateZTree(String permissionGroupId, List<Map<String, Object>> list,
                                                    Map<String, List<UserAccount>> userAccountMap,
                                                    Map<String, List<SysAccountPermission>> sysAccountPermissionMap,
                                                    SysCompany sysCompany, UserAccount account) {
        Map<String, Object> map = null;
        List<UserAccount> userAccounts = userAccountMap.get(sysCompany.getCompanyId());
        if (userAccounts != null && !userAccounts.isEmpty()) {
            map = new HashMap<>();
            map.put("id", sysCompany.getCompanyId());
            map.put("pId", 0);
            map.put("name", sysCompany.getCompanyName());
            //map.put("chkDisabled", true);
            map.put("isParent", true);
            map.put("accountIdentification", "0");
            list.add(map);
            for (UserAccount userAccount : userAccounts) {
                map = new HashMap<>();
                map.put("id", userAccount.getAccountId());
                map.put("pId", sysCompany.getCompanyId());
                map.put("name", userAccount.getUserName());
                map.put("accountIdentification", "1");
                if (account.getAccountId().equals(userAccount.getAccountId())) {
                    map.put("chkDisabled", true);
                }
                List<SysAccountPermission> sysAccountPermissions = sysAccountPermissionMap.get(userAccount.getAccountId());
                boolean isHavePermissions = isHavePermissions(permissionGroupId, sysAccountPermissions);
                if (isHavePermissions) {
                    map.put("checked", true);
                }
                list.add(map);
            }
        }
        return list;
    }

    /**
     * 账号是否有权限
     *
     * @param permissionGroupId
     * @param sysAccountPermissions
     * @return
     */
    private boolean isHavePermissions(String permissionGroupId, List<SysAccountPermission> sysAccountPermissions) {
        boolean isHavePermissions = false;
        if (sysAccountPermissions != null && !sysAccountPermissions.isEmpty()) {
            for (SysAccountPermission sysAccountPermission : sysAccountPermissions) {
                if (permissionGroupId.equals(sysAccountPermission.getPermissionGroupId())) {
                    isHavePermissions = true;
                    break;
                }
            }
        }
        return isHavePermissions;
    }

    /**
     * 获取所有账号
     *
     * @param
     * @return {@link {java.util.List<com.crm.model.entity.sys.UserAccount>}}
     * @Author pym
     * @Date 2021/3/17 10:21
     */
    @Override
    public List<UserAccount> getAllAccountList() {
        List<UserAccount> userAccounts = userAccountDbService.getAllAccountList();
        return userAccounts;
    }

    /**
     * 修改用户密码
     *
     * @param userPassword 新密码
     * @param oldPassword  旧密码
     * @return 1：成功 2：原密码输入错误 3：密码验证不通过
     * @Author renshaorong
     * @Date 2021/3/30
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Short updateUserPassword(String userPassword, String oldPassword) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        if (!this.verifyOldPassword(oldPassword, userAccount)) {
            //存入修改密码记录表
            UpdatePsw updatePsw = new UpdatePsw(CommonUtils.getGUID(),userAccount.getAccountId(), userAccount.getUserAccount(), oldPassword, userPassword, userAccount.getAccountId(), new Date(), (short)1);
            updatePswDbService.insert(updatePsw);
            return (short)2;
        }
        if (!CheckPasswordUtils.isPasswordAvailable(userPassword)){
            //存入修改密码记录表
            UpdatePsw updatePsw = new UpdatePsw(CommonUtils.getGUID(),userAccount.getAccountId(), userAccount.getUserAccount(), oldPassword, userPassword, userAccount.getAccountId(), new Date(), (short)1);
            updatePswDbService.insert(updatePsw);
            return (short)3;
        }
        String md5Password = getMd5Password(userPassword, userAccount.getSalt());//密码加密
        userAccount.setUserPassword(md5Password);
        userAccount.setUpdateTm(new Date());
        boolean b =  userAccountDbService.updateUserAccountByUserId(userAccount);
        if (b){
            userAccountRedisService.addUserAccountPassword(userAccount,userPassword);
            //发送邮箱
            UserInfo userInfo = userInfoDbService.selectUserInfoByUserId(userAccount.getUserId());
            String sendTitle = "关于crm系统账号修改说明";
            String sendText = "您的crm系统账号修改成功，账号："+userInfo.getUserEmail()+" ;密码："+userPassword;
            SendEamil.sendEamil(sendTitle,sendText,userAccount.getUserAccount());
        }
        //存入修改密码记录表
        UpdatePsw updatePsw = new UpdatePsw(CommonUtils.getGUID(),userAccount.getAccountId(), userAccount.getUserAccount(), oldPassword, userPassword, userAccount.getAccountId(), new Date(), (short)(b ? 2 : 1));
        updatePswDbService.insert(updatePsw);
        return (short)1;
    }

    /**
     * 获取md5，散列1024次后的密码
     *
     * @param userPassword 密码
     * @param salt         盐
     * @return
     * @Author renshaorong
     * @Date 2021/4/8
     */
    public String getMd5Password(String userPassword, String salt) {
        return new SimpleHash("MD5", userPassword, salt, 1024).toString();//密码加密
    }

    /**
     * 验证原密码是否正确
     *
     * @param userPassword 当前密码
     * @return
     * @Author renshaorong
     * @Date 2021/3/30
     */
    @Override
    public Boolean verifyPassword(String userPassword) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        return this.verifyOldPassword(userPassword, userAccount);
    }

    /**
     * @param userPassword
     * @param userAccount  用户
     * @return
     * @Author renshaorong
     * @Date 2021/4/2
     * 验证密码是否正确
     */
    public Boolean verifyOldPassword(String userPassword, UserAccount userAccount) {
        userPassword = getMd5Password(userPassword, userAccount.getSalt());//密码加密
        return userAccount.getUserPassword().equals(userPassword);
    }


    /**
     * 获取账号列表
     *
     * @param pageIndex     页码
     * @param pageSize      分页大小
     * @param userAccountQO 查询实体
     * @param sortName      排序列名称
     * @param sortOrder     排序规则(asc/desc)
     * @return
     * @Author renshaorong
     * @Date 2021/4/7
     */
    @Override
    public DhPageInfo<UserAccountManagerVO> selectUserAccountPage(Integer pageIndex, Integer pageSize, UserAccountQO userAccountQO, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }

        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        boolean rs = CommonUtils.isAdmin(userAccount.getUserId());
        //单元测试时给默认值
//        boolean rs = CommonUtils.isAdmin("0");

        //增加删除状态查询条件(0:正常;1:已删除)
        userAccountQO.setDeleteStatus((short) StatusCodeEnum.NORMAL_CODE.getState());

        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch (sortName) {
                case "createTm": {
                    order.append("a.create_tm ").append(sortOrder);
                }
                break;
                default:
                    break;
            }
        }
        List<UserAccountManagerVO> userAccountList = new ArrayList<UserAccountManagerVO>();
        if (rs) {
            //超级管理员
            userAccountList = userAccountDbService.selectAllUserAccountList(userAccountQO, order.toString());
        } else {
            //普通管理员
            userAccountQO.setCompanyId(userAccount.getCompanyId());
            //单元测试时给默认值
//            userAccountQO.setCompanyId("9fa2dde1393311eb9e0a00163e08893d");
            userAccountList = userAccountDbService.selectUserAccountListByCompanyId(userAccountQO, order.toString());
        }
        PageInfo<UserAccountManagerVO> pageInfo = new PageInfo<UserAccountManagerVO>(userAccountList);
        return new DhPageInfo<UserAccountManagerVO>(pageInfo, userAccountList);
    }

    /**
     * 初始化密码为初始值
     *
     * @param accountId user_account表主键
     * @return
     * @Author renshaorong
     * @Date 2021/4/8
     */
    @Override
    public boolean initialPassword(String accountId) {
        UserAccount userAccount = userAccountDbService.selectUserAccountByAccountId(accountId);
        UserInfo userInfo = userInfoDbService.selectUserInfoByUserId(userAccount.getUserId());
        UserAccount localUser = (UserAccount) SecurityUtils.getSubject().getPrincipal();
        String oldPassword = userAccount.getUserPassword();
        String password;
        if (userInfo.getOnTheJobSituation() == 1){//离职
            password = "000000";
        } else {
            password = CheckPasswordUtils.getRandomPsw(6);
        }
        String userPassword = getMd5Password(password, userAccount.getSalt());//密码加密
        userAccount.setUserPassword(userPassword);
        userAccount.setUpdateTm(new Date());
        boolean b = userAccountDbService.updateUserAccountByPrimaryKeySelective(userAccount);
        if (b){
            userAccountRedisService.addUserAccountPassword(userAccount,password);
            //发送邮箱
            String sendTitle = "关于crm系统账号修改说明";
//            String sendText = "您的crm系统账号重置成功，账号："+userAccount.getUserAccount()+" ;密码："+password;
            String sendText = "您的crm系统账号重置成功，账号："+userInfo.getUserEmail()+" ;密码："+password;
            SendEamil.sendEamil(sendTitle,sendText,userAccount.getUserAccount());
        }
        //存入修改密码记录表
        UpdatePsw updatePsw = new UpdatePsw(CommonUtils.getGUID(),userAccount.getAccountId(), userAccount.getUserAccount(), oldPassword, password, localUser.getAccountId(), new Date(), (short)(b ? 2 : 1));
        updatePswDbService.insert(updatePsw);
        return b;
    }

    /**
     * 测试redis的key是否覆盖
     * @return
     */
    @Override
    public Boolean getList() {
        List<UserAccount> list = userAccountDbService.getAllAccountList();
        return userAccountRedisService.addUserAccount(list);
    }

    @Override
    public JSONObject addUserAccountAndUserInfo(UserAccountAddQO userAccountAddQO) {

        JSONObject result = new JSONObject();
        //判断账号是否存在
        if ("1".equals(userAccountAddQO.getIfTestAccount())) {
            userAccountAddQO.setUserAccount(userAccountAddQO.getUserEmail());
        }
        Boolean ifExist = userAccountDbService.selectUserAccountByAccountName(userAccountAddQO.getUserAccount());
        if (ifExist) {
            result.put("isExist", true);
        } else {
            UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
            //是否是超级管理员
            Boolean ifSuperAdmin = false;
            if (!"1".equals(userAccountAddQO.getIfTestAccount())) {
                ifSuperAdmin = CommonUtils.isAdmin(userAccount.getUserId());
            }
            Date newDate = new Date();
            String userId = CommonUtils.getGUID();
            //用户信息表添加数据
            UserInfo userInfo = new UserInfo();
            BeanUtils.copyProperties(userAccountAddQO, userInfo);
            userInfo.setUserId(userId);
            userInfo.setCreateTm(newDate);
            userInfo.setUpdateTm(newDate);
            userInfo.setOnTheJobSituation(0);
            if (!ifSuperAdmin) {
                if ("1".equals(userAccountAddQO.getIfTestAccount())) {
                    //是系统测试人员，设置公司
                    userInfo.setCompanyId("9885f68e2401446ba67d14af909ad0a8");
                    userInfo.setCompanyName("CRM测试组");
                    userInfo.setOperateId("71902468-8dee-4e30-b554-456d2140c7d9");
                    userInfo.setUpdateUserId("71902468-8dee-4e30-b554-456d2140c7d9");
                } else {
                    userInfo.setCompanyId(userAccount.getCompanyId());
                    userInfo.setOperateId(userAccount.getAccountId());
                    userInfo.setUpdateUserId(userAccount.getAccountId());
                    SysCompany sysCompany = sysCompanyDbService.selectSysCompanyById(userAccount.getCompanyId());
                    if (sysCompany != null) {
                        userInfo.setCompanyName(sysCompany.getCompanyName());
                    }
                }
            } else {
                userInfo.setOperateId(userAccount.getAccountId());
                userInfo.setUpdateUserId(userAccount.getAccountId());
            }
            userInfoService.insertUserInfo(userInfo);

            //账号表添加数据
            String accountId = CommonUtils.getGUID();
            UserAccount userAccountAdd = new UserAccount();
            BeanUtils.copyProperties(userAccountAddQO, userAccountAdd);
            //如果是测试人员设置邮箱为账号
            if ("1".equals(userAccountAddQO.getIfTestAccount())) {
                userAccountAdd.setUserAccount(userAccountAddQO.getUserEmail());
                userAccountAdd.setOperateId("71902468-8dee-4e30-b554-456d2140c7d9");
            } else {
                userAccountAdd.setOperateId(userAccount.getAccountId());
            }
            userAccountAdd.setAccountId(accountId);
            userAccountAdd.setUserPassword("e0e6ff4ec8d0344606b16090d029273c");
            userAccountAdd.setSalt("456");
            userAccountAdd.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            userAccountAdd.setCreateTm(newDate);
            userAccountAdd.setUpdateTm(newDate);
            userAccountAdd.setAccountStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));
            userAccountAdd.setUserId(userId);
            userAccountAdd.setSysId("2");
            userAccountAdd.setDeptId("1");
            userAccountAdd.setPositionId("1");
            if (!ifSuperAdmin) {
                if ("1".equals(userAccountAddQO.getIfTestAccount())) {
                    userAccountAdd.setCompanyId("9885f68e2401446ba67d14af909ad0a8");
                    //暂时先将公司名称存到部门id上
                    userAccountAdd.setDeptId(userAccountAddQO.getCompanyName());
                } else {
                    userAccountAdd.setCompanyId(userAccount.getCompanyId());
                }
            }
            Boolean rs = userAccountDbService.insertUserAccount(userAccountAdd);
            if(rs) {
                //往redis里面新增用户信息
                UserAccount user = userAccountDbService.selectUserAccountByName(userAccountAddQO.getUserAccount());
                if(user != null) {
                    userAccountRedisService.addRedisUser(user);
                }
                userAccountRedisService.addUserAccountPassword(userAccountAdd,"123456");
            }

            //更新user表的accountId
            UserInfo userInfoUpdate = new UserInfo();
            userInfoUpdate.setUserId(userId);
            userInfoUpdate.setAccountId(accountId);
            userInfoService.updateUserInfo(userInfoUpdate);
            result.put("isExist", false);

            //如果是测试人员给测试人员添加权限
            if ("1".equals(userAccountAddQO.getIfTestAccount())) {
                SysAccountPermission sysAccountPermission = new SysAccountPermission();
                sysAccountPermission.setAccountPermissionId(CommonUtils.getGUID());
                sysAccountPermission.setAccountId(accountId);
                sysAccountPermission.setPermissionGroupId("35b5a2649dd44c8694f0abbc2fb159e8");
                sysAccountPermission.setCreatePeopleId("71902468-8dee-4e30-b554-456d2140c7d9");
                sysAccountPermission.setCreatePeopleName("superadmin");
                sysAccountPermission.setCreateTm(new Date());
                sysAccountPermissionDbService.insertSysAccountPermission(sysAccountPermission);
            }
        }
        return result;
    }

    /**
     * 禁用
     *
     * @param accountId
     * @return
     */
    @Override
    public boolean disableByAccountId(String accountId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setAccountId(accountId);
        userAccount.setAccountStatus((short) 1);
        Boolean rs = userAccountDbService.updateUserAccountByPrimaryKeySelective(userAccount);
        if(rs) {
            //往redis里面覆盖用户信息
            UserAccount user = userAccountDbService.selectUserAccountByAccountId(accountId);
            if(user != null) {
                userAccountRedisService.addRedisUser(user);
            }
        }
        return rs;
    }

    /**
     * 修改分机号
     *
     * @param accountId       账号ID
     * @param extensionNumber 分机号
     * @return {@link {boolean}}
     * @Author pym
     * @Date 2021/5/26 15:47
     */
    @Override
    public String updateExtensionNumber(String accountId, String extensionNumber) {
        Boolean result = userAccountDbService.selectUserAccountByExtensionNumber(extensionNumber);
        if (result) {
            return "U000002";//分机号已存在
        }
        UserAccount userAccount = new UserAccount();
        userAccount.setAccountId(accountId);
        userAccount.setExtensionNumber(extensionNumber);
        Boolean updateUserAccountResult = userAccountDbService.updateUserAccountByPrimaryKeySelective(userAccount);
        return updateUserAccountResult ? "U000000" : "U000001";//U000000修改分机号成功 U000001修改分机号失败
    }

    /**
     * 导入账号信息
     *
     * @param list
     * @return
     */
    @Override
    public JSONObject importUserAccount(List<UserAccountImportVO> list, String companyId, Integer type) throws ParseException {
        //返回的结果集
        JSONObject jsonObject = new JSONObject();
        //导入数量
        int importNum = 0;
        //重复的行数
        String repeatIdStr = "";
        //失败行数
        String importFailIdStr = "";
        for (int i = 0; i < list.size(); i++) {
            boolean b =true;
            UserAccountImportVO importVO = list.get(i);
            List<ImportFailureLogVO> logVOList = importFailureLogDbService.selectImportFailureLogByNameAndType(importVO.getUserAccount(),5,companyId,null);
            if (logVOList.size() > 0){
                for (int k=0;k<logVOList.size();k++){
                    if (logVOList.get(k).getImportData().equals(JSONObject.toJSONString(importVO))){
                        if (logVOList.get(k).getLogType().equals("1")){
                            //重复
                            if (StringUtils.isBlank(repeatIdStr)) {
                                repeatIdStr = String.valueOf(i + 1);
                            } else {
                                repeatIdStr = repeatIdStr + "," + String.valueOf(i + 1);
                            }
                        }else if (logVOList.get(k).getLogType().equals("2")){
                            //导入失败
                            if (StringUtils.isBlank(importFailIdStr)) {
                                importFailIdStr = String.valueOf(i + 1);
                            } else {
                                importFailIdStr = importFailIdStr + "," + String.valueOf(i + 1);
                            }
                        }
                        b =false;
                        break;
                    }
                }
            }
            if (b){

                //查询账号是否存在
                UserAccountManagerVO userAccount = userAccountDbService.selectUserAccountCount(importVO.getUserName(), importVO.getUserAccount(), companyId);
                if (Objects.isNull(userAccount) || Objects.isNull(userAccount.getAccountId())) {
                    Date createTm = null;
                    if (Objects.nonNull(importVO.getCreateTm())) {
                        //同一个Excel有不一样的时间格式……
                        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd");
/*                        int index = importVO.getCreateTm().indexOf(":");
                        if (index != -1 && importVO.getCreateTm().substring(index + 1).indexOf(":") != -1) {
                            simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                        }*/
                        createTm = simpleDateFormat.parse(importVO.getCreateTm());
                    }
                    //6位随机数密码
                    int flag = new Random().nextInt(999999);
                    if (flag < 100000) {
                        flag += 100000;
                    }
                    UserAccount newUserAccount = new UserAccount();
                    UserInfo userInfo = new UserInfo();
                    String md5Password = getMd5Password(String.valueOf(flag), ProjectBusinessConstant.ACCOUNT_PASSWORD_SALT);//密码加密
                    newUserAccount.setUserPassword(md5Password);
                    newUserAccount.setSalt(ProjectBusinessConstant.ACCOUNT_PASSWORD_SALT);
                    newUserAccount.setAccountId(CommonUtils.getGUID());
                    newUserAccount.setUserName(importVO.getUserName());
                    newUserAccount.setUserAccount(importVO.getUserAccount());
                    newUserAccount.setPositionDuty(importVO.getPositionDuty());
                    newUserAccount.setCreateTm(createTm);
                    newUserAccount.setUpdateTm(new Date());
                    newUserAccount.setDeleteStatus(Short.valueOf("0"));
                    newUserAccount.setCompanyId(companyId);
                    if (Objects.nonNull(importVO.getAccountStatus()) && importVO.getAccountStatus().indexOf("启用") != -1) {
                        newUserAccount.setAccountStatus(Short.valueOf("0"));
                    } else {
                        newUserAccount.setAccountStatus(Short.valueOf("1"));
                    }
                    b = userAccountDbService.insertUserAccount(newUserAccount);
                    if (b) {
                        userInfo.setUserId(CommonUtils.getGUID());
                        userInfo.setAccountId(newUserAccount.getAccountId());
                        userInfo.setUserName(importVO.getUserName());
                        userInfo.setUserEmail(importVO.getUserAccount());
                        userInfo.setUpdateTm(new Date());
                        userInfo.setCompanyId(companyId);
                        userInfo.setUserEmail(importVO.getUserAccount());
                        SysCompany sysCompany = sysCompanyDbService.selectSysCompanyById(companyId);
                        userInfo.setCompanyName(sysCompany.getCompanyName());
                        if (type == 1 && Objects.nonNull(importVO.getOnTheJobSituation()) && "在职".equals(importVO.getOnTheJobSituation())) {
                            userInfo.setOnTheJobSituation(0);
                        } else {
                            userInfo.setOnTheJobSituation(1);
                        }
                        if (type == 2) {
                            userInfo.setOnTheJobSituation(1);
                        }
                        userInfo.setUserContact(importVO.getUserContact());
                        userInfo.setCreateTm(createTm);
                        b = userInfoService.insertUserInfo(userInfo);
                    }
                    if (b) {
                        newUserAccount.setUserId(userInfo.getUserId());
                        userAccountDbService.updateUserAccountByPrimaryKeySelective(newUserAccount);
                        importNum = importNum + 1;
                        userAccountRedisService.addUserAccountPassword(newUserAccount, String.valueOf(flag));
                        String sendTitle = "关于crm系统账号创建说明";
                        String sendText = "您的crm系统账号创建成功，账号：" + importVO.getUserAccount() + " ;密码：" + flag;
                        //测试期间不发送邮件
                        //SendEamil.sendEamil(sendTitle,sendText,importVO.getUserAccount());
                    } else {
                        insertImportFailureLog(importVO, 2, companyId, "数据错误");
                        //导入失败
                        if (StringUtils.isBlank(importFailIdStr)) {
                            importFailIdStr = String.valueOf(i + 1);
                        } else {
                            importFailIdStr = importFailIdStr + "," + String.valueOf(i + 1);
                        }
                    }
                    //getAccountId 不为null的话表示插入账号表成功
                    if (!b && Objects.nonNull(newUserAccount.getAccountId())) {
                        userAccountDbService.deleteUserAccountById(newUserAccount.getAccountId());
                    }
                } else {
                    //insertImportFailureLog(importVO, 1, companyId, "第"+i + 1+"行，"+importVO.getUserAccount()+"账号已存在");
                    //重复
                    if (StringUtils.isBlank(repeatIdStr)) {
                        repeatIdStr = String.valueOf(i + 1);
                    } else {
                        repeatIdStr = repeatIdStr + "," + String.valueOf(i + 1);
                    }
                }

            }

        }
        jsonObject.put("importCallNum", importNum);
        jsonObject.put("repeatIdStr", repeatIdStr);
        jsonObject.put("importFailIdStr", importFailIdStr);
        return jsonObject;
    }

    /**
     * 记录导入失败日志
     *
     * @param importVO
     * @param type
     */
    public void insertImportFailureLog(UserAccountImportVO importVO, Integer type, String companyId, String reasonForFailure) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        ImportFailureLog importFailureLog = new ImportFailureLog();
        if (type == 1) {
            UserAccountManagerVO userAccountManagerVO = userAccountDbService.selectUserAccountCount(importVO.getUserName(), importVO.getUserAccount(), companyId);
            importFailureLog.setDataId(userAccountManagerVO.getAccountId());
        }
        importFailureLog.setImportFailureLogId(CommonUtils.getGUID());
        importFailureLog.setOperatePeopleId(userAccount.getAccountId());
        importFailureLog.setOperateTime(new Date());
        importFailureLog.setOperateType("5");
        importFailureLog.setImportName(importVO.getUserAccount());
        importFailureLog.setReasonForFailure(reasonForFailure);
        importFailureLog.setImportData(JSONObject.toJSONString(importVO));
        importFailureLog.setLogType(String.valueOf(type));
        importFailureLog.setCompanyId(companyId);
        importFailureLogDbService.insertImportFailureLog(importFailureLog);
    }

    @Override
    public boolean enableByAccountId(String accountId) {
        UserAccount userAccount = new UserAccount();
        userAccount.setAccountId(accountId);
        userAccount.setAccountStatus((short) 0);
        Boolean rs =  userAccountDbService.updateUserAccountByPrimaryKeySelective(userAccount);
        if(rs) {
            //往redis里面覆盖用户信息
            UserAccount user = userAccountDbService.selectUserAccountByAccountId(accountId);
            if(user != null) {
                userAccountRedisService.addRedisUser(user);
            }
        }
        return rs;
    }

    /**
     * 发送邮件告诉用户密码
     *
     * @param companyId
     */
    @Override
    public void sendUserPasswordToMail(String companyId) {
        List<UserAccount> list = userAccountDbService.selectUserAccountByCompanyId(companyId);
        userAccountRedisService.sendUserPasswordToMail(list);
    }

    /**
     * 把离职用户密码发送到邮箱
     *
     * @param companyId
     */
    @Override
    public void sendLeaveUserPasswordToMail(String companyId, String sendMail) {
        List<UserAccountManagerVO> list = userAccountDbService.selectLeaveUserAccountByCompanyId(companyId);
        if (list.size() > 0) {
            userAccountRedisService.sendLeaveUserPasswordToMail(list, sendMail);
        }
    }

    /**
     * 阶段性停用
     *
     * @param accountId
     * @param deacType
     * @param deacToTime
     * @return
     * @Author renshaorong
     * @Date 2021/6/24
     */
    @Override
    public boolean saveDeacByAccountId(String accountId, String deacType, String deacToTime) {
        UserAccount userAccount = userAccountDbService.selectUserAccountByAccountId(accountId);
        userAccount.setDeactivate((short) 1);
        userAccount.setDeacTime(new Date());
        userAccount.setDeacToTime(DateUtil.parseDate(deacToTime));
        userAccount.setDeacType(deacType);
        return userAccountDbService.updateUserAccountByPrimaryKeySelective(userAccount);
    }

    /**
     * 离职
     * @Author renshaorong
     * @Date 2021/7/2
     * @param accountId
     * @return
     */
    @Override
    public boolean resignByAccountId(String accountId) {
        UserAccount userAccount = userAccountDbService.selectUserAccountByAccountId(accountId);
        UserInfo userInfo = userInfoDbService.selectUserInfoByUserId(userAccount.getUserId());
        userInfo.setOnTheJobSituation(1);
        userInfo.setLeaveTm(new Date());
        userInfo.setUpdateUserId(((UserAccount)SecurityUtils.getSubject().getPrincipal()).getUserId());
        userInfo.setUpdateTm(new Date());
        return userInfoDbService.updateUserInfoByUserId(userInfo);
    }




    /**
     * @Description: 获取分公司下的账号列表
     * @Param: []
     * @Return: java.util.List<com.crm.model.entity.sys.UserAccount>
     * @Author: lixq-f
     * @Date: 2021/6/28
     **/
    @Override
    public List<UserAccount> getAccountListByCompanyId() {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息

        boolean isSuperManage = CommonUtils.isAdmin(userAccount.getUserId());

        List<UserAccount> list = null;
        if (!isSuperManage) {
            //普管
            list = userAccountDbService.selectUserAccountByCompanyId(userAccount.getCompanyId());
        }else {
            //超管
            list = userAccountDbService.getAllAccountList();
        }

        return Optional.ofNullable(list).orElse(new ArrayList<>());
    }

    /**
     * @Description: 获取所有在职且未禁用账号列表
     * @Param: []
     * @Return: java.util.List<com.crm.model.entity.sys.UserAccount>
     * @Author: lixq-f
     * @Date: 2021/7/27
     **/
    @Override
    public List<UserAccountManagerVO> getAllUsedAccountList() {
        return userAccountDbService.getAllUsedAccountList();
    }

    /***
     * @Description:查询客服部人员列表
     * @Param:
     * @Author: luojie
     * @Date: 2021/11/9 14:17
     */
    @Override
    public List<JSONObject> selectReviewerList() {
        List<JSONObject> result = new ArrayList<>();
        SysCompany sysCompany = sysCompanyDbService.selectSysCompanyByName("客服部");
        if(sysCompany!=null){
            List<UserAccount> userAccountList = userAccountDbService.selectUserAccountByCompanyId(sysCompany.getCompanyId());
            userAccountList.stream().forEach(userAccount -> {
                JSONObject jsonObject = new JSONObject();
                jsonObject.put("accountId",userAccount.getAccountId());
                jsonObject.put("userName",userAccount.getUserName());
                result.add(jsonObject);
            });
        }
        return result;
    }

    /**
     * 查询用户
     * @return
     */
    @Override
    public List<UserAccountManagerVO> selectUserList(String companyId) {
        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();//当前登录人信息
        return userAccountDbService.selectUserList(companyId,userAccount.getAccountId());
    }


//    /**
//     * 检查当前登陆用户密码是否过于简单
//     * @return
//     */
//    @Override
//    public boolean checkSimplePassword(){
//        UserAccount userAccount = (UserAccount) SecurityUtils.getSubject().getPrincipal();
//        CheckPasswordUtils.
//    }
}
